package com.xiaxiang.xiawan.Home;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.util.Log;
import android.view.ContextMenu;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.TextView;

import com.dg.acb.utils.configdata.XXConstants;
import com.donggua.aichebao.commonui.refresh.RefreshListener;
import com.donggua.aichebao.commonui.refresh.XXPullToRefreshRecyclerView;
import com.third.share.ShareData;
import com.xiaxiang.xiawan.Home.Adapter.VideoRefreshAdapt;
import com.xiaxiang.xiawan.R;
import com.xiaxiang.xiawan.Ui.WaitDialog;
import com.xiaxiang.xiawan.Util.XXToolUtil;
import com.xiaxiang.xiawan.XXConfigData;
import com.xiaxiang.xiawan.XXMainApplication;
import com.xiaxiang.xiawan.adapt.OnItemClickListener;
import com.xiaxiang.xiawan.dialog.XXDeleteDlg;
import com.xiaxiang.xiawan.share.XXShareDialog;
import com.xiaxiang.xiawan.task.DownloadEffectTask;
import com.xiaxiang.xiawan.view.CustomPullToRefreshRecyclerView;
import com.xiaxiang.xiaxwan.ar.data.XXARMaterialVideoData;
import com.xx.xiawan.net.DGJsonResult;
import com.xx.xiawan.net.DGRequestListener;
import com.xx.xiawan.net.DeleteRequest;
import com.xx.xiawan.net.GetRequest;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;

/**
 * Created by Administrator on 2017-11-27.
 */

public class HomeFragmentOperator {
    private View mMainView;
    //  private ShowreelAdapter adpter;
    private String mVideoUrl = "";
    private ArrayList<HomeData> mHomeDataList = new ArrayList<HomeData>();
    private Handler mUiHandler;
    private HomeData mSelectHomeData;
    private HomeData mLastSelectData;
    private static final int ERROR = 1001;
    private WaitDialog mWaitDialog;
    private int mSelectIndex = -1;
    private DownloadEffectTask mDownloadEffectTask;
    private VideoRefreshAdapt mAdapt;
    private SwipeRefreshLayout mRefreshLayout;
    private CustomPullToRefreshRecyclerView mPullToRefreshRecyclerView;
    private final static int REFRESH = 1;
    private final static int LOADMORE = 2;
    private final static int DELETE = 20001;
    private final static int GET_DATA_ERROR = 20002;
    private final static int REFRESH_DATA_ERROR = 20003;
    private int mLoadStyle  = REFRESH;
    private RecyclerView mRecyclerView;
    private int mDeleteIndex = -1;
    private int mTotalNum = 0;
    private int mPageCount = 0;//总页数
    private int mPageNo = 1;//
    private final static int PER_PAGE_SIZE = 6;
    protected Activity mAct;
    protected String mUrl;
    protected XXMainApplication app;
    protected TextView tvLoadError;
    public HomeFragmentOperator(Activity act,String url,View view){
        mAct = act;
        mUrl = url;
        mMainView = view;
    }

    private void setUiHadler(){
        mUiHandler = new Handler(Looper.getMainLooper()){
            public void handleMessage(Message msg){
                Intent intent;
                XXARMaterialVideoData data;
                super.handleMessage(msg);
                closeDialog();
                switch (msg.what){
                    case 0:
                        if(mLoadStyle == REFRESH){
                            mAdapt.clearData();
                            tvLoadError.setVisibility(View.GONE);
                            mPullToRefreshRecyclerView.setVisibility(View.VISIBLE);
                        }else{
                            // mAdapt.hideFooter();
                        }
                        mPullToRefreshRecyclerView.onRefreshComplete();
                        ArrayList<HomeData> dataList = (ArrayList<HomeData>)msg.obj;
                        int size = dataList.size();
                        Log.e("vi"," size is "+size);
                        for(int i=0;i<size;i++){
                            mAdapt.addHomeDataByChange(dataList.get(i));
                        }
                        mAdapt.notifyDataSetChanged();
                        break;
                    case DownloadEffectTask.SHOW_DIALOG:
                        showDialog();
                        break;
                    case DownloadEffectTask.START_SHOW:
                        String materialName = (String)msg.obj;
                        intent = new Intent("com.xiaxiang.xiawan.video");
                        intent.setAction("com.xiaxiang.xiawan.video");
                        intent.setPackage(getActivity().getPackageName());
                        data = new XXARMaterialVideoData();
                        data.mVideoPath = mSelectHomeData.mVideoUrl;
                        data.setNeedVideoPath(true);
                        data.mMaterialId = mSelectHomeData.mMaterialId;
                        data.mMaterialUrl =mSelectHomeData.mMterialUrl;
                        data.mVideoId = mSelectHomeData.mId;
                        data.mUserName = mSelectHomeData.mUserName;
                        data.mName = mSelectHomeData.mName;
                        data.mMaterialPathName = materialName;
                        data.mArMode = 1;
                        data.mHeadPhoto = mSelectHomeData.mHeadPhoto;
                        data.setNeedVideoPath(true);
                        intent.putExtra(XXToolUtil.MATERIAL_VIDEO_DATA_KEY,data);
                        getActivity().startActivity(intent);
                        break;
                    case DELETE:
                        mAdapt.deleteHomeData(mDeleteIndex);
                        mDeleteIndex = -1;
                        closeDialog();
                        break;
                    case ERROR:
                        closeDialog();
//                        XXToolUtil.showTip(getActivity(),(String)msg.obj);
                        intent = new Intent("com.xiaxiang.xiawan.video");
                        intent.setAction("com.xiaxiang.xiawan.video");
                        intent.setPackage(getActivity().getPackageName());
                        data = new XXARMaterialVideoData();
                        data.mVideoPath = mSelectHomeData.mVideoUrl;
                        data.setNeedVideoPath(true);
                        data.mMaterialId = mSelectHomeData.mMaterialId;
                        data.mMaterialUrl =mSelectHomeData.mMterialUrl;
                        data.mVideoId = mSelectHomeData.mId;
                        data.mUserName = mSelectHomeData.mUserName;
                        data.mName = mSelectHomeData.mName;
                        data.mMaterialPathName = "";
                        data.mArMode = 1;
                        data.mHeadPhoto = mSelectHomeData.mHeadPhoto;
                        data.setNeedVideoPath(true);
                        intent.putExtra(XXToolUtil.MATERIAL_VIDEO_DATA_KEY,data);
                        getActivity().startActivity(intent);
                        break;
                    case GET_DATA_ERROR:
                        mPullToRefreshRecyclerView.onRefreshComplete();
                        closeDialog();
                        XXToolUtil.showTip(getActivity(),(String)msg.obj);
                        break;
                    case REFRESH_DATA_ERROR:
                        if(mAdapt.getItemCount() > 0){
                        }else{
                            tvLoadError.setVisibility(View.VISIBLE);
                           // mPullToRefreshRecyclerView.setVisibility(View.GONE);
                        }
                        mPullToRefreshRecyclerView.onRefreshComplete();
                        closeDialog();
                        XXToolUtil.showTip(getActivity(),(String)msg.obj);
                        break;
                }
                // adpter.notifyDataSetChanged();
            }
        };
    }

    public void initView(int recyclerViewId){
        app = XXMainApplication.getInstance();
        mPullToRefreshRecyclerView = (CustomPullToRefreshRecyclerView) mMainView.findViewById(recyclerViewId);
        tvLoadError = (TextView)mMainView.findViewById(R.id.tvLoadError);
        mPullToRefreshRecyclerView.setHasPullUpFriction(false); // 设置没有上拉阻力
        mRecyclerView = mPullToRefreshRecyclerView.getRefreshableView();
        mRecyclerView.setLayoutManager(new StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL));

        // Set a listener to be invoked when the list should be refreshed.
        mPullToRefreshRecyclerView.setOnRefreshListener(new RefreshListener<XXPullToRefreshRecyclerView>()
        {
            @Override
            public void onPullDownToRefresh(XXPullToRefreshRecyclerView refreshView) {
                mPageNo = 1;
                getVideoInformation(mPageNo,PER_PAGE_SIZE,REFRESH);
            }

            @Override
            public void onPullUpToRefresh(XXPullToRefreshRecyclerView refreshView) {

                if(((mPageNo - 1) * PER_PAGE_SIZE) < mTotalNum){
                    getVideoInformation(mPageNo,PER_PAGE_SIZE,LOADMORE);
                }
            }
        });

        mAdapt = new VideoRefreshAdapt(this.getActivity(),mHomeDataList);
        mRecyclerView.setAdapter(mAdapt);
        mAdapt.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                mSelectHomeData  = mHomeDataList.get(position);
                //download(mSelectHomeData.mMterialUrl);
                if(mSelectIndex == position){
                    mDownloadEffectTask.startDownload(mSelectHomeData.mMterialUrl,mSelectHomeData.mMd5);
                }else{
                    mDownloadEffectTask.startDownload(mSelectHomeData.mMterialUrl,mSelectHomeData.mMd5);
                    if(mSelectHomeData != mLastSelectData){
                        mSelectHomeData.mIsSelect = true;
                        if(mLastSelectData != null){
                            mLastSelectData.mIsSelect = false;
                        }
                        mAdapt.notifyDataSetChanged();
                    }
                }
                mSelectIndex = position;
                mLastSelectData = mSelectHomeData;
            }

            @Override
            public void onItemLongClick(View view, int position) {
                //mDeleteDlg.showInCenter();
                mDeleteIndex = position;
                mRecyclerView.showContextMenu();
            }
        });
        mWaitDialog = new WaitDialog(getActivity());
        getVideoInformation(mPageNo,PER_PAGE_SIZE,REFRESH);
        setUiHadler();
        mDownloadEffectTask = new DownloadEffectTask(getActivity(),mUiHandler);
        mDownloadEffectTask.start();
    }

    private void showDialog(){
        //mWaitDialog.showDialog();
    }

    private void closeDialog(){
        //mWaitDialog.closeDialog();
    }

    private void getVideoInformation(final int start, int pageNumber, final int style){
        showDialog();
        String url = getUrl(start,pageNumber);
        mLoadStyle = style;
        DGRequestListener listener = new DGRequestListener() {
            @Override
            public void onSuccess(DGJsonResult result) {
                Log.e("vi"," getVideoInformation result is "+result.result);
                try {
                    JSONObject object = new JSONObject(result.result);
                    mTotalNum = object.getInt("total");
                    JSONArray array = object.getJSONArray("rows");
                    int size = array.length();
                    ArrayList<HomeData> homeDataList = new ArrayList<HomeData>(size);
                    for(int i=0;i<size;i++){
                        JSONObject json = array.getJSONObject(i);
                        Log.e("vi"," json index is "+i+" json is "+json.toString());
                        HomeData data = new HomeData();
                        data.setJSONData(json);
                        homeDataList.add(data);
                    }
                    mPageNo++;
                    Message msg = mUiHandler.obtainMessage();
                    msg.what = 0;
                    msg.obj = homeDataList;
                    mUiHandler.sendMessage(msg);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onError(String error) {
                Message msg = mUiHandler.obtainMessage();
                if(mLoadStyle == REFRESH){
                    msg.what = REFRESH_DATA_ERROR;
                }else{
                    msg.what = GET_DATA_ERROR;
                }
                msg.obj = error;
                mUiHandler.sendMessage(msg);
            }
        };
        GetRequest request = new GetRequest(url,getActivity(),listener);
        if (app != null) {
            String token = app.getToken();
            if (token != null && token.length() > 0) {
                request.header("token", token);
            }
        }
        request.startNoLock();
    }

    private  String getUrl(int pageNo,int pageSize ){
        // http://121.196.213.86:8089/v1/material/materialListByCategryId?pageNo=1&pageSize=20&categryId=1
        StringBuilder builder = new StringBuilder();
        String dy = "=";
        String a = "&";
        builder.append(mUrl);
        builder.append("?");
        builder.append("pageNo");
        builder.append(dy);
        builder.append(pageNo);
        builder.append(a);
        builder.append("pageSize");
        builder.append(dy);
        builder.append(pageSize);
        if (app != null) {
            String machine_id = app.getMachineId();
            builder.append(a);
            builder.append("machine_id");
            builder.append(dy);
            builder.append(machine_id);
        }
        return builder.toString();
    }

    private class MyDeleteDlg extends XXDeleteDlg {
        public int mDeleteIndex = -1;
        public int mWidth = 0;
        public MyDeleteDlg(Activity activity,int width) {
            super(activity);
            mWidth = width;
            Log.e("wd"," mWidth is "+width);
            this.setWidth(width);
        }
        public void doOnClick(View view){
            int id = view.getId();
            if(id == R.id.btnDelete){
                if(mDeleteIndex != -1 ){
                    deleteHomeData(mDeleteIndex);
                }
            }
            close();
        }
    }

    private void deleteHomeData(int index){
        if(index == -1){
            return;
        }
        HomeData homeData = mHomeDataList.get(index);
        if(homeData != null){
            int id = homeData.mId;
            String url = XXConstants.HTTP_HOME_DEL_URL + "?id=" + id;
            DGRequestListener listener = new DGRequestListener() {
                @Override
                public void onSuccess(DGJsonResult result) {
                    mUiHandler.sendEmptyMessage(DELETE);
                }

                @Override
                public void onError(String error) {
                    Message msg = mUiHandler.obtainMessage();
                    msg.what = ERROR;
                    msg.obj = error;
                    mUiHandler.sendMessage(msg);
                }
            };
            showDialog();
            DeleteRequest deleteRequest = new DeleteRequest(url,getActivity(),listener);
            deleteRequest.startNoLock();
        }

    }

    protected  Activity getActivity(){
        return mAct;
    }

    public void onResume(){
       // getVideoInformation(1,20,REFRESH);
    }

    public void onHiddenChanged(boolean hidden) {
        if(hidden){
            // mARMediaOperator.onPause();
        }else{
            //mARMediaOperator.onResume();
            if(mTotalNum == 0){
                getVideoInformation(mPageNo,PER_PAGE_SIZE,REFRESH);
            }
        }
    }
}
